package com.zxlspace.thread;


import java.util.Hashtable;

public class SynDemo01 {

    public static void main(String[] args) {
        //真实角色
        Web12306 web12306 = new Web12306();
        //代理角色：持有真实角色的引用
        Thread t1 = new Thread(web12306, "路人甲");
        Thread t2 = new Thread(web12306, "黄牛");
        Thread t3 = new Thread(web12306, "攻城狮");
        //二者实现了相同的接口
        t1.start();
        t2.start();
        t3.start();

        Hashtable hashtable = new Hashtable();
        hashtable.put("11", "112");
    }
}

class Web12306 implements Runnable {
    private int num = 50;
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
           test3();
        }
    }

    public void test1() {
        if (num <= 0) {
            this.flag = false;
            return;
        }

        try {
            Thread.sleep(500); //休眠500毫秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "抢到了" + num--);
    }

    //synchronized 修饰方法
    public synchronized void test2() {
        if (num <= 0) {
            this.flag = false;
            return;
        }

        try {
            Thread.sleep(500); //休眠500毫秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "抢到了" + num--);
    }

    //synchronized 修饰代码块
    public void test3() {
        synchronized (this) { //this 代表当前线程资源
            if (num <= 0) {
                this.flag = false;
                return;
            }

            try {
                Thread.sleep(500); //休眠500毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "抢到了" + num--);
        }
    }
}
